package org.ko.core.logic.auth.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.ko.core.dao.auth.PermissionDao;
import org.ko.core.dao.auth.RoleDao;
import org.ko.core.dao.support.Updater;
import org.ko.core.domain.auth.Permission;
import org.ko.core.domain.auth.Role;
import org.ko.core.logic.auth.PermissionSvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;

/**
 * 
 * PermissionSvcImpl
 * @author zengxm 药膏
 * @date 2014-9-19
 * @version 1.0.0
 */
@Service
@Transactional
public final class PermissionSvcImpl implements PermissionSvc{

	@Autowired
	private PermissionDao dao;
	@Autowired
	private RoleDao roleDao;
	
	@Override
	public Permission get(Long id) {
		Permission per = dao.get(id);
		Assert.notNull(per, "权限实体不存在");
		return per;
	}

	@Override
	public Permission addDo(Permission per) {
		Assert.notNull(per, "权限实体不能为空");
		Assert.hasText(per.getPermission(), "权限代码不正确");
		
		System.out.println(per.getId());
		if(per.getId()!=null && per.getId()>0){
			Updater<Permission> updater = new Updater<Permission>(per);
			updater.exclude("parent");
			
			dao.updateByUpdater(updater);
		}else{
			per.setId(null);
			System.out.println(per.getParent()+"  pid="+per.getParent().getId());
			/*
			 * 判断是否为顶级权限
			 * 如果顶级权限，格式应该为： 由字母跟数字组成的字符串（长度在1至20间
			 * 在shiro验证权限时，我们会自动填充‘:*’，最终的格式类似： user:*
			 * 
			 * 代表了user分组下的全部权限都具备了
			 */
			if(per.getParent().getId() == null){
				per.setParent(null);
				
				Assert.isTrue(per.getPermission().matches("[0-9A-Za-z]{1,20}"), "权限命名不正确");
			}
			
			System.out.println(per.getParent()+"  :    ");
			dao.save(per);
		}
		return per;
	}

	/**
	 * on 2014-9-22 01:59:46
	 * 处理了联级删除问题 
	 */
	@Override
	public void delete(Long[] ids) {
		dao.delete(ids);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Permission> findAll() {
		Criteria cri = dao.createCriteria(Restrictions.isNull("parent"));
		cri.addOrder(Order.desc("sort"));
		
		return cri.list();
	}

	@Override
	public void assignToRole(ModelMap model, Long roleId) {
		Role role = roleDao.get(roleId);
		Assert.notNull(role, "角色不存在");
		
		
		//获取角色的权限
		StringBuilder rolePerSB = new StringBuilder(",");
		List<Permission> rolePers = role.getPermissions();
		for(Permission p:rolePers)
			rolePerSB.append(p.getId()+",");
		
		//获取全部的权限分组
		List<Permission> pers = findAll();
		
		model.addAttribute("permissionList", pers);
		model.addAttribute("permissionStr", rolePerSB.toString());
		model.addAttribute("role", role);
	}

	@Override
	public void assignToRoleDo(ModelMap model, Long roleId, Long[] ids) {
		Role role = roleDao.get(roleId);
		Assert.notNull(role, "角色不存在");
		
		//先清空原来的权限
		List<Permission> pList = role.getPermissions();
		pList.clear();
		
		for(Long l:ids){
			Permission per = new Permission();
			per.setId(l);
			
			role.getPermissions().add(per);
		}
		
		Updater<Role> updater = new Updater<Role>(role);
		roleDao.updateByUpdater(updater);
	}
	
}